using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Identity.Infrastructure.Entities;
using Microsoft.AspNetCore.Identity;
using OpenIddict.Server;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace Identity.HttpAPI.Host.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
        {
            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            return services;
        }

        public static IServiceCollection AddOpenIddictServerWithClaims(this IServiceCollection services)
        {
            services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                })
                .AddServer(options =>
                {
                    options.SetAuthorizationEndpointUris("/connect/authorize")
                           .SetTokenEndpointUris("/connect/token")
                           .SetUserInfoEndpointUris("/connect/userinfo");

                    options.AllowAuthorizationCodeFlow()
                           .RequireProofKeyForCodeExchange()
                           .AllowRefreshTokenFlow();

                    // 注册自定义声明类型
                    options.RegisterClaims("role", "permission");

                    options.RegisterScopes(Scopes.OpenId, Scopes.Profile, Scopes.Email, Scopes.OfflineAccess, "api");

                    options.UseAspNetCore()
                           .EnableAuthorizationEndpointPassthrough();//
                                                                     //.EnableTokenEndpointPassthrough(); // 让 /connect/token 由 OpenIddict 默认处理

                    options.AddDevelopmentSigningCertificate();
                    options.AddEphemeralEncryptionKey()
                           .AddEphemeralSigningKey();
                    options.DisableAccessTokenEncryption();

                })
                .AddValidation(options =>
                {
                    options.UseLocalServer();
                    options.UseAspNetCore();
                });

            return services;
        }
    }

}